package net.mayee.alice.spring.exception;

import com.google.common.collect.Lists;
import jodd.log.Logger;
import jodd.log.LoggerFactory;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class AliceHandlerExceptionResolver extends
        SimpleMappingExceptionResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(AliceHandlerExceptionResolver.class);

    public static List<String> ALL_EXCEPTION_LIST = Lists.newArrayList();
    public static String UNAUTHC_EXP = "UNAUTHC_EXP";
    public static String BIND_EXP = "BIND_EXP";
    public static String IO_EXP = "IO_EXP";
    public static String SQL_EXP = "IO_EXP";
    public static String OTHERS_EXP = "OTHERS_EXP";

    static {
        ALL_EXCEPTION_LIST.add(UNAUTHC_EXP);
        ALL_EXCEPTION_LIST.add(BIND_EXP);
        ALL_EXCEPTION_LIST.add(IO_EXP);
        ALL_EXCEPTION_LIST.add(SQL_EXP);
        ALL_EXCEPTION_LIST.add(OTHERS_EXP);
    }

    protected ModelAndView doResolveException(
            javax.servlet.http.HttpServletRequest httpServletRequest,
            javax.servlet.http.HttpServletResponse httpServletResponse,
            java.lang.Object o, java.lang.Exception e) {

        if (e instanceof UnauthorizedException) {
            LOGGER.error(UNAUTHC_EXP, e);
        } else if (e instanceof BindException) {
            LOGGER.error(BIND_EXP, e);
        } else if (e instanceof IOException) {
            LOGGER.error(IO_EXP, e);
        } else if (e instanceof SQLException) {
            LOGGER.error(SQL_EXP, e);
        } else {
            LOGGER.error(OTHERS_EXP, e);
        }
        return super.doResolveException(httpServletRequest,
                httpServletResponse, o, e);
    }

}
